<script setup>
import {ref} from 'vue'
import {useRouter} from "vue-router";
import {_register} from "../api/user.js";
import {errorMsg, succesMsg} from "../util/box.js";
import {isEmail} from "../util/email.js";

const router = useRouter()
const ruleFormRef = ref()

const ruleForm = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
  ],
})

const registerUser = ref({
  username: "",
  password: "",
  confirmPassword: "",
  email: "",
})

const register = async () => {
  if ( !isEmail(registerUser.value.email) ) {
    return
  }
  await _register(registerUser.value).then(res => {
    if ( res.success ) {
      succesMsg("注册成功")
      registerUser.value = {
        username: "",
        password: "",
        confirmPassword: "",
        email: "",
      }
      router.push({path: '/login'})
    }
  })
}

const validateRegister = async (formEl) => {
  await formEl.validate((valid, _) => {
    if (valid) {
      register();
    }
  })
}

</script>

<template>
  <div class="login-form">
    <el-card style="width: 40%">
      <el-form
          ref="ruleFormRef"
          label-position="right"
          label-width="auto"
          :model="registerUser"
          :rules="ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerUser.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="registerUser.password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input type="password" v-model="registerUser.confirmPassword" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="email" v-model="registerUser.email" />
        </el-form-item>
      </el-form>
      <el-space class="login-button">
        <el-link style="margin-right: 20px; color: blue" @click="router.push({path: '/login'})">有账号, 去登录</el-link>
        <el-button @click="validateRegister(ruleFormRef)">注册</el-button>
      </el-space>
    </el-card>
  </div>
</template>

<style scoped>
.login-form {
  display: flex;
//width: 50%;
  margin-top: 10%;
  justify-content: center;
  align-items: center;
}
.login-button {
  float: right;
  margin-top: 20px;
  margin-bottom: 20px;
}
</style>